import moment from 'moment';
import _ from 'lodash';
import { getCssVariableValue } from '@/utils/utils';

const FIRST_CODE = 't'; // 表格首列自定义key
const TIME_MAP = {
  // 24点位
  24: Array.from({ length: 24 }, (v, i) => {
    let hh = i + 1;
    hh = hh < 10 ? '0' + hh : hh;
    return `${hh}00`;
  }),
  // 96点位
  96: Array.from({ length: 97 }, (v, i) => {
    let hh = Math.floor(i / 4);
    let mm = 15 * (i % 4) || '00';
    hh = hh < 10 ? '0' + hh : hh;
    return `${hh}${mm}`;
  }).slice(1),
};

// 模块名称&单位
export const DATA_MAP = {
  spotPrice: { group: 'g1', name: '现货价格', unit: '单位：元/MWh' },
  provinceLoadLinkNewEnergy: { group: 'g1', name: '省内负荷&联络线-新能源', unit: '单位：MW' },
  biddingSpace: {
    name: '竞价空间',
    group: 'g1',
    unit: '单位：MW',
  },
  biddingSpaceCorrelationMap: {
    name: '现货价格&竞价空间相关性',
    tooltip:
      '“竞价空间”是指需以市场化竞价结果进行结算的负荷部分，由于各省披露数据有限，这里以“省内负荷&联络线-新能源”进行代替，会存在少量偏差，特别提醒所有用户',
  },
  provinceLoadLink: { group: 'g1', name: '省内负荷&联络线', unit: '单位：MW' },
  provinceLoadNewEnergy: { group: 'g1', name: '省内负荷-新能源', unit: '单位：MW' },
  newEnergy: { group: 'g1', name: '新能源', unit: '单位：MW' },
  baseDecompositionProportion: { group: 'g1', name: '基数分解比例', unit: '单位：%' },
  provinceLoad: { group: 'g1', name: '省内负荷', unit: '单位：MW' },
  link: { group: 'g1', name: '联络线', unit: '绝对值 单位：MW' },
  setTheStandby: { group: 'g1', name: '备用信息', unit: '单位：MW' },

  zoneElectricityPrice: { group: 'g1', name: '分区电价', unit: '单位元/MWh' },
  spotInformationTieLine: { group: 'g1', name: '日前系统间联络线总输电曲线预测', unit: '单位：MW' },
  releaseSectionPowerForecast: { group: 'g1', name: '关键断面输电能力预测', unit: '单位：MW' },
  operationRealtimePowerFlow: { group: 'g1', name: '重要通道实际输电情况', unit: '单位：MW' },
  realTimeOutputOfTheUnit: { group: 'g1', name: '机组实时出力情况', unit: '单位：MW' },

  unifiedDispatchLoad: { group: 'g1', name: '统调负荷', unit: '单位：MW' },
  outputNewEnergyAllProvince: { group: 'g1', name: '全省新能源出力', unit: '绝对值 单位：MW' },

  totalOutputOfNonmarketizedGeneratingUnits: {
    group: 'g1',
    name: '非市场化机组总出力',
    unit: '单位：MW',
  },
  totalOutputOfHydropowerIncludingPumpedStorage: {
    group: 'g1',
    name: '水电含抽蓄总出力',
    unit: '单位：MW',
  },
  connectingLine: { group: 'g1', name: '联络线', unit: '绝对值 单位：MW' },
  provincialLoad: { group: 'g1', name: '省内负荷', unit: '单位：MW' },
  backupInformation: { group: 'g1', name: '备用信息', unit: '单位：MW' },
};

// 系列配置映射
export const COLOR_MAP = {
  backspinStandby: { type: 'line', color: '#994B42' },
  baseDecompositionProportionActual: { type: 'line', color: '#E86452' },
  baseDecompositionProportionD2: { type: 'line', color: '#A8C9F9' },
  baseDecompositionProportionD3: { type: 'line', color: '#5E92F6' },
  dwD1Forecast: { type: 'dashed', color: '#A8C9F9' },
  dwD2Forecast: { type: 'dashed', color: '#5E92F6' },
  dwD3Forecast: { type: 'dashed', color: '#2B5DB6' },
  oneSourceD1Forecast: { type: 'dashed', color: '#C8EDDC' },
  oneSourceD2Forecast: { type: 'dashed', color: '#67DCAB' },
  oneSourceD3Forecast: { type: 'dashed', color: '#316A47' },
  topspinStandby: { type: 'line', color: '#F5C2B8' },
  realtime: { type: 'line', color: '#E86452' },
  realtimePrice: { type: 'line', color: '#E86452' },
  revisedRealtimePrice: { type: 'line', color: '#E86452' },
  recentlyPrice: { type: 'dashed', color: '#5E92F6' },
  revisedRecentlyPrice: { type: 'dashed', color: '#5E92F6' },
  '330kV河上双回线': { type: 'dashed', color: '#2174FF' },
  '330kV八玉一线': { type: 'dashed', color: '#3CB1FB' },
  '750kV河武双回线、沙鱼双回线、河白线': { type: 'dashed', color: '#07A872' },
  '750kV沙鱼双回线、敦高三回西线': { type: 'dashed', color: '#D29E08' },
  '750kV沙鱼双回线、高泉三回西线': { type: 'dashed', color: '#ED8139' },
  祁韶近区风电总加: { type: 'dashed', color: '#FB6E77' },
  '330kV玉门#1、#2主变': { type: 'dashed', color: '#FF70CF' },
  '750kV河白一线、750kV武白双回、750kV宁官双回': { type: 'dashed', color: '#B382F0' },
  '750kV河泉双回线、沙鱼双回线、甘泉I线、甘河I线': { type: 'dashed', color: '#575FA1' },
  '330kV高布双回': { type: 'dashed', color: '#075288' },
  '330kV山上双回线': { type: 'dashed', color: '#994B42' },
  '750kV武白双回、750kV河白双回、750kV官东双回': { type: 'dashed', color: '#E86452' },
  '110kV萧甜双回线': { type: 'dashed', color: '#A8C9F9' },
  '750kV河武双回线、沙鱼双回线': { type: 'dashed', color: '#07A872' },
  '750kV高泉双回线、沙鱼双回线': { type: 'dashed', color: '#D29E08' },
  '750kV敦高双回线、沙鱼双回线': { type: 'dashed', color: '#ED8139' },
  '750kV泉河双回线、沙鱼双回线': { type: 'dashed', color: '#FB6E77' },
  '甘肃-青海日前': { type: 'dashed', color: '#2174FF' },
  '甘肃-陕西日前': { type: 'dashed', color: '#3CB1FB' },
  '甘肃-湖南日前': { type: 'dashed', color: '#07A872' },
  '甘肃-宁夏日前': { type: 'dashed', color: '#D29E08' },
  合计日前: { type: 'dashed', color: '#ED8139' },
  '甘肃-新疆日前': { type: 'dashed', color: '#FB6E77' },

  newEnergy: { type: 'line', color: '#2174FF' },
  nonMarketActualPower: { type: 'line', color: '#3CB1FB' },
  photovoltaic: { type: 'line', color: '#07A872' },
  hydraulicActualPower: { type: 'line', color: '#D29E08' },
  wind: { type: 'line', color: '#ED8139' },

  actual: { type: 'line', color: '#E86452' },
  forecast: { type: 'dashed', color: '#A8C9F9' },
  '华北来电-预测': { type: 'dashed', color: '#2174FF' },
  '昭沂直流-预测': { type: 'dashed', color: '#3CB1FB' },
  '银东直流-预测': { type: 'dashed', color: '#07A872' },
  '鲁固直流-预测': { type: 'dashed', color: '#D29E08' },
  预测备用信息上旋: { type: 'dashed', color: '#2174FF' },
  预测备用信息下旋: { type: 'dashed', color: '#3CB1FB' },
  预测风电总加: { type: 'dashed', color: '#2174FF' },
  预测光伏总加: { type: 'dashed', color: '#3CB1FB' },
  预测新能源总加: { type: 'dashed', color: '#07A872' },
};

/**
 * 获取表格数据
 * @param {*} charts 处理好的图表配置
 * @param {*} stationName 场站名称
 * @returns 表格数据
 */
export const getTableData = ({ charts, stationName, tableKeys }) => {
  return tableKeys.map((key) => {
    let groupTitle = '';
    const { name = '', unit = '' } = DATA_MAP[key] || {};
    if (key === 'spotPrice') {
      groupTitle += `${stationName} `;
    }
    groupTitle += name;
    if (unit) {
      groupTitle += `（${unit || ''}）`;
    }
    const series = charts?.[key]?.series || [];
    return {
      id: key,
      groupTitle,
      children: series.map((seri) => {
        let temp = {};
        temp[FIRST_CODE] = seri.name;
        temp.id = `${key}_${seri.name}`;
        seri.data.map((v, i) => {
          temp[i + 1] = v;
        });
        return temp;
      }),
    };
  });
};

/**
 * 获取表头数据
 * @param {*} param0 开始日期startDate, 结束日期endDate, 点位类型type[24, 96]
 * @returns 表头数据
 */
export const getTableColumns = ({ startDate, endDate, type }) => {
  let dateCol = [];
  const days = moment(endDate).diff(moment(startDate), 'day');
  for (let i = 0; i <= days; i++) {
    const date = moment(startDate).add(i, 'day').format('MMDD');
    const temp = TIME_MAP[type].map((time, j) => ({
      name: `${date} ${time}`,
      code: `${i * type + j + 1}`,
      width: 90,
      align: 'center',
    }));
    dateCol = dateCol.concat(temp);
  }
  return [{ code: FIRST_CODE, name: '类型', width: 240, lock: true }, ...dateCol];
};

// 特殊处理: 现货价格&竞价空间相关性
const getScatterOption = (d) => {
  let timelineData = [];
  let options = [];
  const removeRepeat = (arr) => {
    const obj = {};
    return arr.filter((item) => {
      const str = item.toString();
      if (!obj[str]) {
        obj[str] = true;
        return item;
      }
      return false;
    });
  };

  for (const date in d) {
    let dayAhead, realtime;
    const tname = date === '全部' ? date : moment(date).format('MMDD');
    timelineData.push(tname);
    const { dayAheadBiddingSpaceCorrelation = [], realtimeBiddingSpaceCorrelation = [] } =
      d[date] || {};
    dayAhead = dayAheadBiddingSpaceCorrelation.map((x) => [x.xAxis, x.value]);
    dayAhead = removeRepeat(dayAhead);
    realtime = realtimeBiddingSpaceCorrelation.map((x) => [x.xAxis, x.value]);
    realtime = removeRepeat(realtime);
    options.push({
      series: [{ data: realtime }, { data: dayAhead }],
    });
  }
  return {
    timeline: {
      data: timelineData,
      title: '日期选择',
      options,
      label: {
        color: getCssVariableValue('--chart-font-color'),
      },
      lineStyle: { color: getCssVariableValue('--chart-x-line') },
      checkpointStyle: {
        symbolSize: 10,
        borderWidth: 2,
        color: 'white',
        borderColor: getCssVariableValue('--bd-primary'),
      },
    },
    grid: { top: 12, left: 48, bottom: 75, right: 75 },
    legend: {
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
    },
    xAxis: [
      {
        scale: true,
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisLine: {
          lineStyle: {
            type: 'solid',
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
      },
    ],
    dataZoom: [
      {
        type: 'slider',
        bottom: 26,
        start: 0,
        end: 100,
        height: 20,
        show: true,
        backgroundColor: getCssVariableValue('--bg-form'),
        dataBackground: {
          dataBackground: {
            areaStyle: { opacity: 0 },
            lineStyle: { opacity: 0 },
          },
        },
        selectedDataBackground: {
          areaStyle: {
            color: getCssVariableValue('--font-primary'),
            opacity: 0.15,
          },
          lineStyle: { color: 'transparent' },
        },
        borderColor: 'transparent',
        handleStyle: {
          color: getCssVariableValue('--bg-form'),
          borderColor: getCssVariableValue('--bd'),
        },
        brushSelect: false,
        showDetail: false,
      },
    ],
    tooltip: {
      formatter: (params) => {
        return params
          .map((x) => {
            const typename = x.seriesIndex === 0 ? '实时' : '日前';
            return `<div style="display:flex;align-items:center;">
                    <div>
                      <div style="display:flex;align-items:center;">
                        <div style="width:8px;height:8px;border-radius:4px;background:${
                          x.color
                        };"></div>
                        <div style="color:#A7A8A9;margin:0 4px;">${typename}价格</div>
                      </div>
                      <div style="display:flex;align-items:center;">
                        <div style="width:8px;height:8px;border-radius:4px;background:${
                          x.color
                        };"></div>
                        <div style="color:#A7A8A9;margin:0 4px;">${typename}竞价空间</div>
                      </div>
                    </div>
                    <div style="color:#A7A8A9;text-align:right;">
                      <div>${x.value?.[1] || '-'}</div>
                      <div>${x.value?.[0] || '-'}</div>
                    </div>
                  </div>`;
          })
          .join('');
      },
    },
    series: [
      {
        type: 'scatter',
        name: '实时价格与竞价空间相关性',
        props: {
          symbolSize: 8,
          legendHoverLink: false,
          itemStyle: { color: '#E86452', borderWidth: 1, borderColor: 'rgba(34, 38, 41, 0.5)' },
          emphasis: { itemStyle: { borderWidth: 1, borderColor: 'rgba(255, 255, 255, 0.85)' } },
        },
      },
      {
        type: 'scatter',
        name: '日前价格与竞价空间相关性',
        props: {
          symbolSize: 8,
          legendHoverLink: false,
          itemStyle: { color: '#5E92F6', borderWidth: 1, borderColor: 'rgba(34, 38, 41, 0.5)' },
          emphasis: { itemStyle: { borderWidth: 1, borderColor: 'rgba(255, 255, 255, 0.85)' } },
        },
      },
    ],
  };
};

/**
 * 返回所有图表配置&表格数据
 * @param {*} data 数据 { name: '我是一条线', data: [], key }
 * @param {array} datetimes 点位
 * @param {string} key 数据标识
 * @param {number} isRevised 修正前1、修正后0
 * @param {string} stationName 场站名称
 * @param {array} tableKeys 表格用到的数据键
 * @returns 所有图表配置、表格数据
 */
export const fmtData = ({ dataMap, datetimes, isRevised, stationName, chartKeys, tableKeys }) => {
  let charts = {};
  // 整理图表配置
  chartKeys.map((key) => {
    let dataList = dataMap?.[key] || [];
    if (key === 'biddingSpaceCorrelationMap') {
      // 特殊处理: 现货价格&竞价空间相关性
      charts[key] = getScatterOption(dataList);
    } else {
      if (key === 'spotPrice') {
        // 现货价格
        const _keys = !!isRevised
          ? ['revisedRealtimePrice', 'revisedRecentlyPrice']
          : ['realtimePrice', 'recentlyPrice'];
        dataList = dataList.filter((x) => _keys.includes(x.lineType));
      }
      // 系列
      const series = dataList.map((x) => ({
        ...(COLOR_MAP[x.lineType] || { type: 'line' }),
        name: x.lineName || '',
        data: _.flatten(Object.values(x.pointData).map((y) => y.map((z) => z.value))),
      }));
      charts[key] = {
        series,
        grid: { top: 12, left: 48, bottom: 72, right: 10 },
        tooltip: {},
        legend: {
          textStyle: {
            color: getCssVariableValue('--chart-legend-color'),
          },
        },
        // dataZoomSlider: true,
        xAxis: [
          {
            type: 'category',
            data: datetimes,
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
            axisLine: {
              lineStyle: {
                type: 'solid',
                color: getCssVariableValue('--chart-x-line'),
              },
            },
            axisTick: {
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
            axisPointer: {
              type: 'line',
              lineStyle: {
                color: getCssVariableValue('--chart-x-line'),
              },
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              color: getCssVariableValue('--chart-font-color'),
            },
            axisTick: {
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
            splitLine: {
              lineStyle: {
                color: getCssVariableValue('--chart-y-line'),
              },
            },
          },
        ],
        dataZoom: [
          {
            type: 'slider',
            bottom: 26,
            start: 0,
            end: 100,
            height: 20,
            show: true,
            backgroundColor: getCssVariableValue('--bg-form'),
            dataBackground: {
              dataBackground: {
                areaStyle: { opacity: 0 },
                lineStyle: { opacity: 0 },
              },
            },
            selectedDataBackground: {
              areaStyle: {
                color: getCssVariableValue('--font-primary'),
                opacity: 0.15,
              },
              lineStyle: { color: 'transparent' },
            },
            borderColor: 'transparent',
            handleStyle: {
              color: getCssVariableValue('--bg-form'),
              borderColor: getCssVariableValue('--bd'),
            },
            brushSelect: false,
            showDetail: false,
          },
        ],
      };
    }
  });
  // 整理表格数据
  const tableData = getTableData({
    charts,
    stationName,
    tableKeys,
  });
  return {
    charts,
    tableData,
  };
};
